package com.fowo.api.syncAmazon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.entity.AmazonShipmentRemovalReport;
import com.fowo.api.entity.TmpShipmentRemovalReport;
import com.fowo.api.mapper.AmazonShipmentRemovalReportMapper;
import com.fowo.api.mapper.TmpShipmentRemovalReportMapper;
import com.fowo.api.syncAmazon.api.RemovalShipmentReportService;
import com.fowo.api.syncAmazon.mapper.AmazonTmpMapper;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class RemoveShipmentServiceImpl extends ServiceImpl<AmazonShipmentRemovalReportMapper, AmazonShipmentRemovalReport> {

    @Resource
    private TmpShipmentRemovalReportMapper tmpShipmentRemovalReportMapper;
    @Resource
    private RemovalShipmentReportService reportService;
    @Resource
    private AmazonTmpMapper amazonTmpMapper;

    /**
     * 同步移除货件
     * @throws Exception
     */
    public void syncRemoveShipment() throws Exception {
        //清空临时表
        amazonTmpMapper.deleteAllShipmentRemovalOrder();
        //拉数据到临时表
        reportService.getRemovalShipment();

        List<TmpShipmentRemovalReport> shipmentRemovalReports = tmpShipmentRemovalReportMapper.selectList(new QueryWrapper<TmpShipmentRemovalReport>().eq("del_flag", 0));
        List<AmazonShipmentRemovalReport> insertList = new ArrayList<>();
        if(shipmentRemovalReports != null && shipmentRemovalReports.size() > 0){
            for (TmpShipmentRemovalReport removalReport:shipmentRemovalReports) {
                QueryWrapper<AmazonShipmentRemovalReport> orderWrapper = new QueryWrapper<>();
                orderWrapper.eq("del_flag",0);
                orderWrapper.eq("order_id",removalReport.getOrderId());
                orderWrapper.eq("sku",removalReport.getSku());
                int count = (int)this.count(orderWrapper);
                if(count > 0){
                    continue;
                }
                AmazonShipmentRemovalReport report = new AmazonShipmentRemovalReport();
                BeanUtils.copyProperties(removalReport, report);
                report.setId(null);
                report.setCreateTime(new Date());
                insertList.add(report);
            }
            List<List<AmazonShipmentRemovalReport>> partition = Lists.partition(insertList, 200);
            for (List<AmazonShipmentRemovalReport> list:partition) {
                this.saveBatch(list);
            }
        }
    }

}
